package com.lyf.controller.admin;

import com.lyf.dto.DishDTO;
import com.lyf.dto.DishPageQueryDTO;
import com.lyf.pojo.Dish;
import com.lyf.result.PageResult;
import com.lyf.result.Result;
import com.lyf.service.DishService;
import com.lyf.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@Api(tags = "菜品管理")
@RequestMapping("/admin/dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询：{}",dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @ApiOperation("查询菜品详情")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        log.info("查询菜品详情：{}",id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    @ApiOperation("新增菜品")
    @PostMapping
    @CachePut(cacheNames = "dishCache", key = "#dishDTO.categoryId")
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}",dishDTO);
        dishService.saveWithFlavor(dishDTO);
        return Result.success();
    }

    @ApiOperation("更新菜品")
    @PutMapping
    @CacheEvict(cacheNames = "dishCache", key = "#dishDTO.categoryId")
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("更新菜品：{}",dishDTO);
        dishService.updateWithFlavor(dishDTO);
        return Result.success();
    }

    @ApiOperation("删除菜品")
    @DeleteMapping
    @CacheEvict(cacheNames = "dishCache", allEntries = true)
    public Result delete(@RequestParam List<Long> ids) {
        log.info("删除菜品id：{}",ids);
        dishService.deleteBatch(ids);
        return Result.success();
    }

    @ApiOperation("菜品启售停售")
    @PostMapping("/status/{status}")
    @CacheEvict(cacheNames = "dishCache", allEntries = true)
    public Result startOrStop(@PathVariable Integer status, @RequestParam Long id) {
        log.info("菜品启售停售：{},{}", status, id);
        Dish dish = DishVO.builder().id(id).status(status).build();
        dishService.startOrStop(dish);
        return Result.success();
    }

    @ApiOperation("根据菜品分类id查询菜品")
    @GetMapping("/list")
    public Result list(Long categoryId) {
        log.info("根据菜品分类id查询菜品：{}",categoryId);
        List<DishVO> results = dishService.list(categoryId);
        return Result.success(results);
    }
}
